import {
  AutoComplete,
  Button,
  Cascader,
  Checkbox,
  Col,
  Form,
  Input,
  InputNumber,
  Row,
  Select,
  Watermark,
  Img,
  DatePicker,
} from "antd";
import React, { useState, useEffect } from "react";
import "./register.css";
import { getArrowToken } from "antd/es/style/roundedArrow";
import { useNavigate, Navigate } from "react-router-dom";
import { addUser } from "../../api";
import axios from 'axios'; 
const { Option } = Select;

// const residences = [
//   {
//     value: "zhejiang",
//     label: "浙江",
//     children: [
//       {
//         value: "hangzhou",
//         label: "河南",
//         children: [
//           {
//             value: "洛阳",
//             label: "洛阳",
//           },
//         ],
//       },
//     ],
//   },
//   {
//     value: "jiangsu",
//     label: "江苏",
//     children: [
//       {
//         value: "nanjing",
//         label: "南京",
//         children: [
//           {
//             value: "zhonghuamen",
//             label: "江宁区",
//           },
//         ],
//       },
//     ],
//   },
// ];
const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 8,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 16,
    },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};

const Register = () => {
  const [form] = Form.useForm();
  const navigate =useNavigate()
  // const [captchaUrl, setCaptchaUrl] = useState(""); // 假设你有一个URL来获取验证码图片
  // const [captchaInput, setCaptchaInput] = useState(""); // 存储用户输入的验证码

  // // 模拟的验证码图片URL生成函数（实际开发中你需要从后端获取）
  // const generateCaptchaUrl = () => {
  //   // 这里只是模拟，实际开发中你会向后端请求一个新的验证码图片URL
  //   // 假设每次请求都会返回一个不同的URL
  //   return `https://example.com/captcha/${Date.now()}`;
  // };

  // 初始化验证码图片URL
  // useEffect(() => {
  //   setCaptchaUrl(generateCaptchaUrl());
  // }, []); // 空数组作为依赖项表示这个effect只会在组件挂载时运行一次
  // // 刷新验证码图片
  // const handleCaptchaRefresh = () => {
  //   setCaptchaUrl(generateCaptchaUrl());
  // };
  const onFinish =async (values) => {

    console.log("Received values of form: ", values);
    console.log("生日",values.birth);
    const response = await axios.post('http://localhost:8091/api/user/register', {  
      username: values.nickname,  
      password: values.password,
      age:values.age,
      birthday:values.birth,
      address:values.residence,
      phoneNumber:values.phone
    }); 
    console.log("注册",response); 
    navigate("/login")
  };
  const prefixSelector = (
    <Form.Item name="prefix" noStyle>
      <Select
        style={{
          width: 70,
        }}
      >
        <Option value="86">+86</Option>
        <Option value="87">+87</Option>
      </Select>
    </Form.Item>
  );
  const suffixSelector = (
    <Form.Item name="suffix" noStyle>
      <Select
        style={{
          width: 70,
        }}
      >
        <Option value="USD">$</Option>
        <Option value="CNY">¥</Option>
      </Select>
    </Form.Item>
  );
  const [autoCompleteResult, setAutoCompleteResult] = useState([]);
  const onWebsiteChange = (value) => {
    if (!value) {
      setAutoCompleteResult([]);
    } else {
      setAutoCompleteResult(
        [".com", ".org", ".net"].map((domain) => `${value}${domain}`)
      );
    }
  };
  const websiteOptions = autoCompleteResult.map((website) => ({
    label: website,
    value: website,
  }));
  return (
    <Watermark content="数字马力">
      <div className="register">
        <div className="content">
          <Form
            {...formItemLayout}
            form={form}
            name="register"
            onFinish={onFinish}
            initialValues={{
              residence: "成员达家",
              prefix: "86",
            }}
            style={{
              maxWidth: 600,
            }}
            scrollToFirstError
          >
            <Form.Item
              name="nickname"
              label="用户名"
              tooltip="您想让别人如何称呼您？"
              rules={[
                {
                  required: true,
                  message: "请输入您的用户名!",
                  whitespace: true,
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="password"
              label="密码"
              rules={[
                {
                  required: true,
                  message: "请输入您的密码!",
                },
              ]}
              hasFeedback
            >
              <Input.Password />
            </Form.Item>

            <Form.Item
              name="confirm"
              label="确认密码"
              dependencies={["password"]}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: "请输入您的确认密码!",
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue("password") === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(
                      new Error(
                        "The new password that you entered do not match!"
                      )
                    );
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              label="年龄"
              name="age"
              rules={[
                {
                  required: true,
                  message: "请输入年龄",
                },
                {
                  type: "number",
                  message: "年龄必须是数字",
                },
              ]}
            >
              <InputNumber placeholder="请输入年龄"></InputNumber>
              </Form.Item>
              <Form.Item
                label="出生日期"
                name="birth"
                rules={[
                  {
                    required: true,
                    message: "请选择出生日期",
                  },
                ]}
              >
                <DatePicker
                  placeholder="请选择"
                  format="YYYY/MM/DD"
                ></DatePicker>
              </Form.Item>
              <Form.Item
                name="residence"
                label="地址"
                rules={[
                  {
                  
                    required: true,
                    message: "请选择您的惯常居所！",
                  },
                ]}
              >
             <Input />
              </Form.Item>
           
            <Form.Item
              name="phone"
              label="手机号"
              rules={[
                {
                  required: true,
                  message: "请输入您的手机号!",
                },
              ]}
            >
              <Input
                addonBefore={prefixSelector}
                style={{
                  width: "100%",
                }}
              />
            </Form.Item>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                {
                  type: "email",
                  message: "请输入正确格式的邮箱：..@..com",
                },
                {
                  required: false,
                  message: "输入你的邮箱",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              name="intro"
              label="简介"
              rules={[
                {
                  required: false,
                  message: "个人简介",
                },
              ]}
            >
              <Input.TextArea showCount maxLength={100} />
            </Form.Item>

            {/* <Form.Item
              label="Captcha"
              extra="We must make sure that you are a human."
            >
              <Row gutter={8}>
                <Col span={12}>
                  <Form.Item
                    name="captcha"
                    noStyle
                    rules={[
                      {
                        required: true,
                        message: "Please input the captcha you got!",
                      },
                    ]}
                  >
                    <Input
                      value={captchaInput}
                      onChange={(e) => setCaptchaInput(e.target.value)}
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <img
                    src={captchaUrl}
                    alt="Captcha"
                    style={{ maxWidth: "100%" }}
                  />

                  <Button type="primary" onClick={handleCaptchaRefresh}>
                    Refresh
                  </Button>
                </Col>
              </Row>
            </Form.Item> */}

            <Form.Item
              name="agreement"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) =>
                    value
                      ? Promise.resolve()
                      : Promise.reject(new Error("Should accept agreement")),
                },
              ]}
              {...tailFormItemLayout}
            >
              <Checkbox>
                我已确认以上<a href="">信息</a>
              </Checkbox>
            </Form.Item>
            <Form.Item {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit">
                注册
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </Watermark>
  );
};

export default Register;
